package adapter;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import com.adgroup.smartnote.CreateGroupActivity;
import com.adgroup.smartnote.LoginActivity;
import com.adgroup.smartnote.R;
import com.adgroup.smartnote.RegisterActivity;
import com.adgroup.smartnote.SearchFriend;
import com.adgroup.smartnote.SmartNoteActivity;
import com.androidquery.AQuery;

import database.Database;

import JsonModel.FamiliarFriend;
import Net.JsonParse;
import Utilities.Configuration;
import Utilities.Utility;
import adapter.AdapterCategories.Holder;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import animationmenu.CollapseAnimation;
import animationmenu.ExpandAnimation;

public class AdapterSearchFriend {
	ArrayList<FamiliarFriend> arr;
	Context c;
	public String userRoot;
	public AdapterSearchFriend(Context c, ArrayList<FamiliarFriend> arr, String string)
	{
		this.c = c;
		this.arr = arr;
		userRoot = string;
	}
	public class Holder
	{
		ImageView iv;
		TextView tv;
		TextView tvEmail;
		Button btn;
	}
	public class Adapter extends BaseAdapter 
	{

		@Override
		public int getCount() {
			return arr.size();
		}

		@Override
		public Object getItem(int arg0) {
			return arr.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}
		int pointed = 0;
		public FamiliarFriend getFamiliarFriend()
		{
			return arr.get(pointed);
		}
		public void setArrayUser(ArrayList<FamiliarFriend> a){
			arr = a;
		}
		public void setUserRoot(String a){
			userRoot = a;
		}
		
		@Override
		public View getView(final int arg0, View arg1, ViewGroup arg2) {
			Holder holder;
			LayoutInflater inflater = ((Activity) c).getLayoutInflater();
			if (arg1 == null) {
				holder = new Holder();
				arg1 = inflater.inflate(R.layout.itemsearchfriend, null);
				holder.tv = (TextView) arg1
						.findViewById(R.id.textViewNicknameSearchLV);
				holder.iv = (ImageView) arg1
						.findViewById(R.id.imageViewLogoSearchLV);	
				holder.tvEmail = (TextView) arg1.findViewById(R.id.textViewEmailSearchLV);
				holder.btn = (Button) arg1.findViewById(R.id.buttonMakeFriend);
				arg1.setTag(holder);
			} else {
				holder = (Holder) arg1.getTag();
			}
			//get model friend
			final FamiliarFriend f = arr.get(arg0);
			holder.tv.setText(f.getNickName());
			holder.tvEmail.setText(f.getGmail());
			
			if(f.getIsAccpet().equalsIgnoreCase("null") || f.getIsAccpet().equalsIgnoreCase("1")){
				holder.btn.setText(c.getResources().getString(R.string.buttonmakefriend));
			}
			else if(f.getIsAccpet().equalsIgnoreCase("0")){
				holder.btn.setText(c.getResources().getString(R.string.buttonmakefriendrequested));
			}
			else if(f.getIsAccpet().equalsIgnoreCase("2")){
				holder.btn.setText(c.getResources().getString(R.string.buttonmadefriendintolist));
			}
			
			AQuery aq = new AQuery(arg1);
			Bitmap placeholder = aq.getCachedImage(R.drawable.imageload);
			aq.id(holder.iv).image(arr.get(arg0).getLink(), true,
						true, 0, 0, placeholder, AQuery.FADE_IN_NETWORK, 1.0f);
			
			
			holder.btn.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View view) {
					if(new Database(c).getUser()==null){//user id = 0
						new AlertDialog.Builder(c)
						.setTitle(c.getResources().getString(R.string.buttonlogin))
						.setMessage(c.getResources().getString(R.string.messagemakefriendlogin))
						.setNegativeButton(c.getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								((SearchFriend)c).userReveive = f;
								Log.d("log",f.getUserId());
								Intent i = new Intent(c, LoginActivity.class);
								((SearchFriend)c).startActivityForResult(i, Configuration.requestMakeFriendToLogin);
							}
						})
						.setPositiveButton(c.getResources().getString(R.string.cancel),
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
									}
						}).show();
					}
					else if(f.getIsAccpet().equalsIgnoreCase("1") || f.getIsAccpet().equalsIgnoreCase("null")){
						new AsynSendRequest(f).execute(new String[]{userRoot,f.getUserId(),f.getNickName(),arg0+""});
					}
					else if(f.getIsAccpet().equalsIgnoreCase("0")){
						new AsynCancelRequest().execute(new String[]{userRoot,f.getUserId(),f.getNickName(),arg0+""});
					}
				}
			});
			return arg1; 
		}

		
	}
	//sent request make friend
	class AsynSendRequest extends AsyncTask<String, Void, String>
	{
		ProgressDialog progress;
		int index;
		FamiliarFriend f;
		public AsynSendRequest(FamiliarFriend f) {
			this.f = f;
		}
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progress = ProgressDialog.show(c, "",
					c.getResources().getString(R.string.titledialogsendmakefriend), true);
		}
		@Override
		protected String doInBackground(String... params) {
			try {
				index = Integer.parseInt(params[3]);
			} catch (Exception e) {
				index = -1;
			}
			return new JsonParse().sendRequestMakeFriend(c, params,f.getUserId());
		}
		@Override
		protected void onPostExecute(String result) {
			try {
				JSONObject json = new JSONObject(result);
				String r = json.getString(Configuration.result);
				if(r.equalsIgnoreCase("-2")){
					Utility.ShowAlert(c, c.getResources().getString(R.string.titledialogmakefriend), c.getResources().getString(R.string.messagemakefriendexist));
				}
				else if(r.equalsIgnoreCase("-1")){
					Utility.ShowAlert(c, c.getResources().getString(R.string.titledialogmakefriend), c.getResources().getString(R.string.messagemakefriendsent));
				}
				else{
					Utility.ShowAlert(c, c.getResources().getString(R.string.titledialogmakefriend), c.getResources().getString(R.string.messagemakefriendsuccess));
					if(index!=-1){
						arr.get(index).setIsAccpet(0+"");
						((SearchFriend)c).updateNotify(arr);
					}
				}
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			progress.dismiss();
			super.onPostExecute(result);
		}		
	}
	//cancel make friend			
	class AsynCancelRequest extends AsyncTask<String, Void, String>
	{
		ProgressDialog progress;
		String nickname = "";
		int index;
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progress = ProgressDialog.show(c, "",
					c.getResources().getString(R.string.titledialogcancelmakefriend), true);
		}
		@Override
		protected String doInBackground(String... params) {
			nickname = params[2];
			try {
				index = Integer.parseInt(params[3]);
			} catch (Exception e) {
				index = -1;
			}
			
			return new JsonParse().sendCancelMakeFriend(c, params);
		}
		@Override
		protected void onPostExecute(String result) {
			Utility.ShowAlert(c, c.getResources().getString(R.string.buttonmakefriendrequested), c.getResources().getString(R.string.messagemakefriendrequested)+" "+nickname);
			progress.dismiss();
			if(index!=-1)
			{
				arr.get(index).setIsAccpet("null");
				((SearchFriend)c).updateNotify(arr);
			}
			super.onPostExecute(result);
		}
	}
}
